#include <string.h>
#include "ESP01s_Control.h"

uint8_t ESP_index = 0;
ESP_State_t ESP_state = ESP_state_START;

void ESP_AutoConnect(void) {
    ESP_index = 0;
    ESP_state = ESP_state_START;
    OLED_ShowString(1, 1, "AUTO START");
    USART_SendString(&USART2_Cfg, (const unsigned char*)at_cmds[0].cmd, at_cmds[0].len); // 发送第一条AT指令
}

/**
 * @brief  检查esp-01s的状态，并且实现重新联网
 * @param  msg.data
 * @retval 无
 * @note   
 */
// ESP_control.c
void ESP_ProcessResponse(char *resp) {
	if(ESP_index >= sizeof(at_cmds)/sizeof(at_cmds[0])) {
		ESP_index = 0; // 防止数组越界
		return;
	}
	
    static uint8_t retry_count = 0;
    const uint8_t max_retry = 3;

    /* 成功响应处理 */
    if(strstr(resp, "OK") || strstr(resp, "WIFI GOT IP")) {
        retry_count = 0; // 重置重试计数器
        
        // 更新状态和显示
		OLED_Clear();
        ESP_state = at_cmds[ESP_index].next_state;
        OLED_ShowString(1, 1, ESP_StateToString(ESP_state));
        
        // 自动发送下一条开机指令
        ESP_index++;
        if(at_cmds[ESP_index].cmd && ESP_index <= 4) {
//			USART_printf(&USART1_Cfg, "[test] ESP01s line42 | %s",(const unsigned char*)at_cmds[ESP_index].cmd);	// test1
            USART_SendString(&USART2_Cfg, (const unsigned char*)at_cmds[ESP_index].cmd, at_cmds[ESP_index].len);
        } else {
            OLED_ShowString(2, 1, "AUTO READY!");
        }
    }
    /* 失败响应处理 */
    else if(strstr(resp, "FAIL") || strstr(resp, "ERROR")) {
        if(++retry_count < max_retry) {
            // 延时后重发当前指令
            vTaskDelay(pdMS_TO_TICKS(1000)); 
            USART_SendString(&USART2_Cfg, (const unsigned char*)at_cmds[ESP_index].cmd, at_cmds[ESP_index].len);
            OLED_ShowString(3, 1, "Retrying...");
        } else {
            // 彻底失败时重置
            retry_count = 0;
            ESP_index = 0;
            ESP_state = ESP_state_START;
            OLED_ShowString(3, 1, "RESETTING...");
            vTaskDelay(pdMS_TO_TICKS(1000));
            ESP_ProcessResponse("FORCE RESTART"); // 触发重新开始
        }
    }
}

const char* ESP_StateToString(ESP_State_t state) {
    static const char* names[] = {
        [ESP_state_START]       = "ESP_AT_TEST",
        [ESP_state_STATIONMode] = "ESP_SET_STA",
        [ESP_state_IPCONNECT]   = "ESP_CONN_WIFI",
        [ESP_state_TCPCONNECT]  = "ESP_CONN_TCP",
        [ESP_state_TRANSPARENT] = "ESP_TRANSMIT",
        [ESP_state_END]         = "READY"
    };
    return names[state];
}

void ESP_SendPacket(void) {
    char payload[MAX_MSG_LEN];
	const char *device_state;
	
	// 1. 读取状态
	uint8_t pin_state = GPIO_ReadOutputDataBit(BUZZER_PORT, BUZZER_PIN);
	device_state = (pin_state == (BitAction)Buzzer_OFF) ? "Buzzer_OFF" : "Buzzer_ON";
	
	// 2. 构建完整HTTP请求
    int payload_len = snprintf(payload, sizeof(payload), "GET /0 HTTP/1.1\r\nuser-agent: STM32\r\n\r\n[Buzzer_state:%s]", device_state);
	
	// 3. 发送原始数据
	// Linux乱码（后面发现其实不是乱码，是vim显示原因）
	payload[payload_len] = '\0';
    USART_printf(&USART2_Cfg, payload);  	

	LED_shortBlink();
}

void vTask_ESP01s_Heartbeat(void *arg){
	while(1){
		if(ESP_state == ESP_state_TRANSPARENT){
			ESP_SendPacket();
		}
		vTaskDelay(30000);
	}
}
